from pml.Parser.lexer.lexer import Lexer
from pml.Parser.lexer.position import Position
from pml.Parser import ASTBuilder
from pml.Bytecode.BytecodeBuilder import BytecodeBuilder
import pickle, os

def compile(file, displayDebug):
    lexer = Lexer(Position(file, open(file), -1, 0, 1))
    tokens = lexer.lexer(None, lexer, position=None)
    if displayDebug:
        print(tokens)
        print()

    builder = ASTBuilder(iter(tokens), depth=1)
    builder.getNextToken()
    ast = builder.buildAST(None, builder, position=None)
    if displayDebug:
        print(ast)
        print()

    builder = BytecodeBuilder(ast)
    bytecodes = builder.buildBytecode(None, builder).obj.value

    if displayDebug:
        for bytecode in bytecodes:
            print(bytecode)
        print()

    with open(os.path.splitext(file)[0] + '.pmc', 'wb') as o:
        pickle.dump(bytecodes, o)
